<?php

namespace app\admin\controller;

use think\Db;
use think\Session;
use think\Validate;

class Home extends Common
{
    public function index()
    {
        $data = Db::name('home')->where(['sys_channel'=>getenv('APP_CHANNEL')])->order('id asc')->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function add()
    {
        $id = input("id");
        if (request()->isAjax()) {
            $post = input('post.');

            if (!isset($post['body']) || !$post['body']) {
                return ['err' => '内容不能为空'];
            }

            $post['body'] = in_content($post['body']);
            $post['update_time'] = time();
            $post['sys_channel'] = geyenv('APP_CHANNEL');
            if (!$id) {   // 添加数据
                $post['create_time'] = $post['update_time'];
                $db = Db::name('home')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {      //修改数据
                $db = Db::name('home')->where('id', $id)->update($post);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('home')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function dele()
    {
        $id = input("id");
        $db = Db::name('home')->delete($id);
        if ($db) {
            $data = ['ret' => '删除成功'];
        } else {
            $data = ['err' => '删除失败'];
        }

        return $data;
    }
}